package cn.fetosoft.woodpecker.core.jmeter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;

/**
 * 加载外部扩展的jar包
 * @author guobingbing
 * @wechat t_gbinb
 * @since 2021/8/8 11:03
 */
public class LoadExtLibsUtil {

    private static final Logger logger = LoggerFactory.getLogger(LoadExtLibsUtil.class);

    /**
     * 加载目录下的所有jar文件
     * @param jarPath
     */
    public static void loadJars(String jarPath){
        File jarDir = new File(jarPath);
        if(jarDir.isDirectory() && jarDir.canRead()){
            File[] jars = jarDir.listFiles();
            try{
                for(File jar : jars){
                    loadURL(jar.toURI().toURL());
                }
            }catch (Exception e){
                logger.error("loadJars", e);
            }
        }
    }

    /**
     * 通过反映将jar包加入系统ClassLoader
     * @param url
     */
    private static void loadURL(URL url){
        if(url!=null){
            Method addUrl = null;
            boolean isAccessible = false;
            try{
                addUrl = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
                isAccessible = addUrl.isAccessible();
                addUrl.setAccessible(true);
                URLClassLoader loader = (URLClassLoader) ClassLoader.getSystemClassLoader();
                addUrl.invoke(loader, url);
            }catch (Exception e){
                logger.error("loadURL", e);
            }finally {
                if(addUrl!=null){
                    addUrl.setAccessible(isAccessible);
                }
            }
        }
    }

    public static void main(String[] args) {
        try{
            LoadExtLibsUtil.loadJars("D:\\Git\\meterweb\\meterweb-web\\lib");
            Class<?> driverClazz = Class.forName("com.mysql.jdbc.Driver");
            System.out.println("DataSourceElement =>" + driverClazz.getDeclaredConstructor().newInstance());
            System.out.println(driverClazz.getClassLoader().toString());
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
